package com.ejlchina.tool.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.databinding.FragmentExtendSerialPortBinding
import com.ejlchina.tool.adapter.DeviceAdapterRadio
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.bean.ExtendSerialPortBean
import com.ejlchina.tool.enums.ExtendSerialPortEnum
import com.ejlchina.tool.enums.OnOffEnum
import com.ejlchina.tool.enums.SuccessFailEnum
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.util.COMMAND_EXTEND_SERIAL_PORT_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_EXTEND_SERIAL_PORT_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_EXTEND_SERIAL_PORT_SET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_EXTEND_SERIAL_PORT_SET_UPWARD
import com.ejlchina.tool.util.bytearray.intTo32HexStringLE
import com.ejlchina.tool.util.bytearray.readByteArrayBE
import com.ejlchina.tool.util.bytearray.readByteArrayLE
import com.ejlchina.tool.util.getBitValueFrom32Bits
import com.ejlchina.tool.util.setBitValue
import com.ejlchina.tool.util.showToast
import com.ejlchina.tool.view.GridItemDecoration
import com.huyuhui.fastble.data.BleDevice

class ExtendSerialPortFragment: BaseBindingFragment2<FragmentExtendSerialPortBinding>() {

    private val extendSerialPortReadBean = ExtendSerialPortBean()


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews(){
        setHeadTitle("扩展串口")
        initListeners()
    }

    private fun initListeners(){
        binding.btnConfirm.setOnClickListener {
            setExtendSerialPortData(deviceAdapter.getSelectDevice())
        }
        binding.msDistance.setOnCheckedChangeListener { _, isChecked ->
            extendSerialPortReadBean.distanceSensor = isChecked
        }
        binding.msWater.setOnCheckedChangeListener { _, isChecked ->
            extendSerialPortReadBean.waterSensor = isChecked
        }
        binding.msWeight.setOnCheckedChangeListener { _, isChecked ->
            extendSerialPortReadBean.weightSensor = isChecked
        }

        binding.msBottle.setOnCheckedChangeListener { _, isChecked ->
            extendSerialPortReadBean.bottleCountSensor = isChecked
        }
    }

    private fun initData(){
        initDevices()
    }

    private fun initDevices(){
        deviceAdapter = DeviceAdapterRadio(GlobalConnectObject.getCurrentConnectDeviceList()){
            getExportSerialPortData(it)
        }
        binding.rvDevices.apply {
            adapter = deviceAdapter
            layoutManager = GridLayoutManager(requireContext(),3)
            if (itemDecorationCount == 0){
                addItemDecoration(GridItemDecoration(3,11,11))
            }
        }
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean, command: String, commandByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice,command, commandByteArray)
        when (command){
            COMMAND_EXTEND_SERIAL_PORT_GET_UPWARD -> {
                val dataByteArray = commandByteArray.readByteArrayLE(1,4)
                setInputSingleBeanData(dataByteArray)
                setUIData()
            }
            COMMAND_EXTEND_SERIAL_PORT_SET_UPWARD -> {
                if (commandByteArray[commandByteArray.size - 1].toInt() == SuccessFailEnum.SUCCESS.value){
                    deviceAdapter.getSelectDevice().isWaterCoverOn = extendSerialPortReadBean.waterSensor
                }
                when(commandByteArray[commandByteArray.size - 1].toInt()){
                    1 -> {
                        showToast("设置成功")
                    }
                    else -> {
                        showToast("设置失败")
                    }
                }
            }
        }
        dismissLoading()
    }

    private fun setExtendSerialPortData(bleDevice: BleDeviceBean){
        setCommandData(bleDevice,COMMAND_EXTEND_SERIAL_PORT_SET_DOWNWARD,getResultData())
    }

    private fun getResultData(): String{
        var npnValue = 0
        if (extendSerialPortReadBean.distanceSensor){
            npnValue = setBitValue(npnValue,0)
        }
        if (extendSerialPortReadBean.waterSensor){
            npnValue = setBitValue(npnValue,1)
        }
        if (extendSerialPortReadBean.weightSensor){
            npnValue = setBitValue(npnValue,2)
        }
        if (extendSerialPortReadBean.bottleCountSensor){
            npnValue = setBitValue(npnValue,3)
        }
        return "07" + intTo32HexStringLE(npnValue)
    }

    private fun setInputSingleBeanData(dataByteArray: ByteArray){
        extendSerialPortReadBean.distanceSensor = getBitValueFrom32Bits(dataByteArray,0) == ExtendSerialPortEnum.OPEN.value
        extendSerialPortReadBean.waterSensor = getBitValueFrom32Bits(dataByteArray,1) == ExtendSerialPortEnum.OPEN.value
        extendSerialPortReadBean.weightSensor = getBitValueFrom32Bits(dataByteArray,2) == ExtendSerialPortEnum.OPEN.value
        extendSerialPortReadBean.bottleCountSensor = getBitValueFrom32Bits(dataByteArray,3) == ExtendSerialPortEnum.OPEN.value
    }

    private fun setUIData(){
        binding.msDistance.isChecked = extendSerialPortReadBean.distanceSensor
        binding.msWater.isChecked = extendSerialPortReadBean.waterSensor
        binding.msWeight.isChecked = extendSerialPortReadBean.weightSensor
        binding.msBottle.isChecked = extendSerialPortReadBean.bottleCountSensor
    }


    private fun getExportSerialPortData(bleDevice: BleDeviceBean){
        getCommandData(bleDevice,COMMAND_EXTEND_SERIAL_PORT_GET_DOWNWARD)
    }

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentExtendSerialPortBinding {
        return FragmentExtendSerialPortBinding.inflate(inflater,container,true)
    }
}